package com.lishe.lishe.lishe.module.mall.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.HttpUtils;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerGriadViewItemDecoration;
import com.lishe.lishe.lishe.MyRecyclerView.RecyclerViewRefreshListener;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshHeaderLayout;
import com.lishe.lishe.lishe.MyRecyclerView.RefreshRecyclerView;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.mall.adapter.MallOtherGoodsBaseAdapter;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.utils.Utils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.Date;
import java.util.LinkedList;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.util.TextUtils;

/**
 * Created by lwa on 2017/9/25.
 * 商城的搜索功能
 */

public class MallSearchActivity extends BaseActivity implements View.OnClickListener {

    private RefreshRecyclerView recyclerView;
    private LinkedList<MallGoods> mallGoods = new LinkedList<>();//列表显示的商品
    private MallOtherGoodsBaseAdapter mallOtherGoodsAdapter;
    private String keywork;
    private Button callBack;
    private TextView title;
    private RelativeLayout empty;
    private TextView emptyText;
    private TextView textView;

    /**
     * @param activity
     * @param keywork  关键字
     */
    public static void jump(Activity activity, String keywork) {
        Intent intent = new Intent(activity, MallSearchActivity.class);
        intent.putExtra("keywork", keywork);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mallsearch);
        keywork = getIntent().getStringExtra("keywork");
        mallOtherGoodsAdapter = new MallOtherGoodsBaseAdapter(MallSearchActivity.this, mallGoods);
        initView();
    }

    private void initView() {
        callBack = findViewById(R.id.title_left_button);
        textView = findViewById(R.id.textView);
        empty = findViewById(R.id.empty);
        emptyText = findViewById(R.id.text);
        empty.setVisibility(View.GONE);
        textView.setText("搜索结果“" + keywork + "”");
        title = findViewById(R.id.title_text_title);
        title.setText(keywork);
        callBack.setOnClickListener(this);
        recyclerView = findViewById(R.id.recycleView);
        recyclerView.setLayoutManager(new GridLayoutManager(MallSearchActivity.this, 2));
        recyclerView.addItemDecoration(new RecyclerGriadViewItemDecoration(Utils.dip2px(MallSearchActivity.this,10),1,1));
        recyclerView.setOnItemClickListener(new RefreshRecyclerView.ItemClickListener() {
            @Override
            public void OnClickListener(RecyclerView.Adapter adapter, View view, int position) {
                MallGoods mall = mallGoods.get(position);
                GoodsDetailActivity.jump(MallSearchActivity.this, mall.getItem_id());
            }
        });

//        recyclerView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
//            @Override
//            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
//                String label = new Date().toLocaleString();
//                // 更新显示的label
//                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
//                getData();
//            }
//        });
        recyclerView.setOnRefreshListener(new RecyclerViewRefreshListener() {
            @Override
            public void onHeaderRefresh(View headerView) {
                String label = new Date().toLocaleString();
                // 更新显示的label
                ((RefreshHeaderLayout) headerView).setLable(label);
                getData();
            }

            @Override
            public void onFooterRefresh(View footerViwe) {
                recyclerView.setFooterRefreshEnabled(false);
            }
        });
        recyclerView.setAdapter(mallOtherGoodsAdapter);
        getData();
    }

    /**
     * 接口拿数据
     */
    private void getData() {
        Log.e("搜索的url", Globals.LISHE_URL + "Goods/search?keywords=" + keywork);
        //token在此处无意义
        if (TextUtils.isEmpty(Globals.getToken())) {
            HttpUtils.get(Globals.LISHE_URL + "Goods/search?keywords=" + keywork, null, goodsDataResposetUrl);
        } else {
            HttpUtils.get(Globals.LISHE_URL + "Goods/search?keywords=" + keywork + "&token=" + Globals.getToken(), null, goodsDataResposetUrl);
        }
    }

    AsyncHttpResponseHandler goodsDataResposetUrl = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            recyclerView.setCompleteRefresh();
            Log.e("链接result", result);
            try {
                JSONObject json = new JSONObject(result);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    if (json.optString("msg").contains("操作成功")) {
                        JSONArray dataArray = json.optJSONArray("data");
                        mallGoods.clear();
                        for (int i = 0; i < dataArray.length(); i++) {//前部分
                            MallGoods mallGood = new MallGoods();
                            JSONObject object = dataArray.optJSONObject(i);
//                            mallGood = JSON.parseObject(object.toString(), MallGoods.class);
                            mallGood.setPrice(object.optString("price"));
                            mallGood.setMkt_price(object.optString("mkt_price"));
                            mallGood.setImage_default_id(object.optString("image_default_id"));
                            mallGood.setItem_id(object.optString("item_id"));
                            mallGood.setShop_id(object.optString("shop_id"));
                            mallGood.setIs_offline(object.optString("is_offline"));
                            mallGood.setTitle(object.optString("title"));
                            mallGood.setWeight(object.optString("weight"));
                            mallGood.setJd_ids(object.optString("jd_sku"));
                            mallGoods.add(mallGood);
                        }
                    } else {
                        toast(json.optString("msg"));
                    }
                    mallOtherGoodsAdapter.notifyDataSetChanged();
                    if (mallGoods.size() == 0) {
                        empty.setVisibility(View.VISIBLE);
                        emptyText.setText("没收搜索到相关商品！");
                    } else {
                        empty.setVisibility(View.GONE);
                    }

                } else {
                    toast(result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("网络或服务器异常！");
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
        }
    }
}
